package main

import (
	"context"
	"flag"
	"fmt"
	"os"

	"go.uber.org/zap"
)

var (
	configFile = flag.String("config", "configs/config.yml", "配置文件路径")
	version    = "1.0.0"
	buildTime  = "unknown"
	gitCommit  = "unknown"
)

func main() {
	flag.Parse()

	// 打印版本信息
	printVersionInfo()

	// 加载配置
	cfg, err := loadConfiguration()
	if err != nil {
		fmt.Printf("加载配置文件失败: %v\n", err)
		os.Exit(1)
	}

	// 初始化日志
	appLogger, err := setupLogger(cfg)
	if err != nil {
		fmt.Printf("初始化日志失败: %v\n", err)
		os.Exit(1)
	}
	defer func() {
		if err := appLogger.Sync(); err != nil {
			fmt.Printf("同步日志失败: %v\n", err)
		}
	}()

	appLogger.Info("应用启动",
		zap.String("version", version),
		zap.String("config_file", *configFile),
		zap.String("build_time", buildTime),
		zap.String("git_commit", gitCommit),
	)

	// 初始化Redis客户端
	redisClient := setupRedis(cfg, appLogger)
	defer redisClient.Close()

	// 初始化服务层
	services := setupServices(redisClient, cfg, appLogger)

	// 验证扫描目录
	validateDirectories(services, appLogger)

	// 创建上下文用于优雅关闭
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 创建Gin路由
	router := setupRouter(cfg)

	// 设置中间件
	setupMiddlewares(router, appLogger)

	// 设置路由
	setupRoutes(router, services, appLogger, cfg)

	// 启动HTTP服务器
	srv := startServer(router, cfg, appLogger)

	// 启动定时任务调度器
	scheduler := startScheduler(services, cfg, appLogger, ctx)

	// 等待信号并优雅关闭
	gracefulShutdown(srv, scheduler, appLogger)
}
